#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include "Common.h"
#pragma comment(lib, "Common.lib")
#pragma comment(lib, "ws2_32.lib")

SOCKET g_connectSocket;
char buf[MAXBUFFSIZE];

void assert(bool b) {if (!b) printf("assert failed.");}

void init(void) {
	WSAData wsaData;
	if( WSAStartup(MAKEWORD(2,2), &wsaData) != 0 ) {
		error("bad WSAStartup");
		return;
	}
}

int sendReq(int op, int val) {
	memset(buf, 0, MAXBUFFSIZE);
	sprintf(buf, "%d %d#", op, val);
	return send(g_connectSocket, buf, strlen(buf), 0);
}

int getServerData(void) {
	fd_set rdfds;
	timeval tv;
	int ret;

	FD_ZERO(&rdfds);
	FD_SET(g_connectSocket, &rdfds);
	tv.tv_sec = 2;
	tv.tv_usec = 0;
	ret = select(g_connectSocket + 1, &rdfds, NULL, NULL, &tv);
	if(ret < 0) error("select error");
	else if(ret == 0) error("timeout");

	if(!FD_ISSET(socket, &rdfds))
		error("not really received data");

	int recvBytes = recv(g_connectSocket, buf, MAXBUFFSIZE, 0);
	buf[recvBytes] = 0;
	ret = -3;
	sscanf(buf, "%d", &ret);
	return ret;
}

void ConnectReq(int userId) {
	if (!sendReq(USER_CONNECT, userId))
		printf("connect request send failed");
}

void ReleaseReq(int userId) {
	if (!sendReq(USER_RELEASE, userId))
		printf("release request send failed");
}

int GetPnodeByUser(int userId) {
	if (!sendReq(USER_GETNODE, userId)) {
		printf("get node request send failed");
		return -2;
	}
	
	return getServerData();
}

unsigned int GetUserNumByPnode(int nodeId) {
	if (!sendReq(NODE_GETNUM, nodeId)) {
		printf("get user number request send failed");
		return -2;
	}

	return getServerData();
}

int main(void)
{
	init();

// 	createConnectSocket();
	createConnectSocket(PORT, LOCALHOST, &g_connectSocket);

	/*** try all test cases, here just an example *****/
	int PnodeId, n;
	int A = 1;

	ConnectReq (A);

	PnodeId = GetPnodeByUser(A);
	assert(PnodeId != -1);

	PnodeId = GetPnodeByUser(A+1);
	assert(PnodeId == -1);

	n = GetUserNumByPnode (PnodeId);
	assert(n == 1);

	ReleaseReq(A);

	n = GetUserNumByPnode (PnodeId);
	assert(n == 0);
	/***************************************************/
	WSACleanup();

	return 0;
}